// pages/outvisit/task/record.js
const recorderManager = wx.getRecorderManager();
const fileSystemManager = wx.getFileSystemManager();
var api = require("../../../utils/api.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prePage: {},//上一个页面实例对象
    userId:0,//用户ID
    outvisitTaskId: 0,//外访任务ID
    type: 3,//文件类型
    collectionCaseId: 0,//催收案件ID
    recordState: 0,//录音状态(0：没有录音;1：正在录音;2：暂停录音)
    recordParam: {
      duration: 600000,//录音最大时长
      numberOfChannels: 1,//录音通道数
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 30//分片大小
    },//录音参数
    recordTime: 0,//录音时间
    recordTimeBegin: 0,//开始录音时的时间戳
    isOccupy:false,//录音是否被占用
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pages = getCurrentPages();//获取页面栈
    var prePage = pages[pages.length - 2];//上一个页面实例对象
    var userId = wx.getStorageSync("userId");
    var outvisitTaskId = options.outvisitTaskId;
    var type = options.type;
    var collectionCaseId = options.collectionCaseId;
    // 设置文件类型
    that.setData({
      prePage: prePage,
      userId: userId,
      outvisitTaskId: outvisitTaskId,
      type: type,
      collectionCaseId: collectionCaseId
    });
    // 获取授权
    that.setAuthorize();
    // 设置录音占用事件
    that.onInterruptionBegin();
    // 设置录音占用结束事件
    that.onInterruptionEnd();
    // 设置录音暂停事件
    that.onPause();
  },

  // 获取授权
  setAuthorize: function () {
    wx.authorize({
      scope: 'scope.record',
      success() {
      }
    });
  },

  // 设置录音占用事件
  onInterruptionBegin: function () {
    var that = this;
    recorderManager.onInterruptionBegin(() => {
      that.setData({
        isOccupy: true
      });
    });
  },

  // 设置录音占用结束事件
  onInterruptionEnd: function () {
    var that = this;
    recorderManager.onInterruptionEnd(() => {
      that.setData({
        isOccupy: false
      });
    });
  },

  // 设置录音暂停事件
  onPause: function () {
    var that = this;
    recorderManager.onPause(res => {
      //结束录音计时 
      clearInterval(that.setInter);
      // if (that.data.isOccupy){
        that.setData({
          recordState: 2,
        });
      // } else {
      //   //继续录音
      //   that.recordResume();
      // }
    });
  },

  // 点击录音
  recordClick: function () {
    var that = this;
    // 防止连续点击
    if (that.justClick) {
      return;
    }
    that.justClick = true;
    setTimeout(() => {
      that.justClick = false;
    }, 1000);

    if (that.data.isOccupy) {
      wx.showToast({
        title: '麦克风被占用中，请稍后再试',
        icon: 'none'
      });
    } else {
      if (that.data.recordState == 0) {// 如果没有开始录音
        //开始录音
        that.recordStart();
      } else if (that.data.recordState == 1) {// 如果正在录音
        //停止录音
        that.recordStop();
      } else if (that.data.recordState == 2) {// 如果录音暂停
        //继续录音
        that.recordResume();
      }
    }
  },

  //开始录音
  recordStart: function () {
    var that = this;
    that.setData({
      recordState: 1
    });
    //开始录音计时   
    that.recordingTimer();
    //开始录音
    recorderManager.start(that.data.recordParam);
    //录音失败
    recorderManager.onError((res) => {
      //结束录音计时 
      clearInterval(that.setInter);
      that.setData({
        recordState: 0,
        recordTime: 0
      });
      if (res.errMsg.indexOf('auth') >= 0) {
        wx.showModal({
          title: '无法录音',
          content: '您已经拒绝访问麦克风，无法使用录音功能，如需使用，请删除此小程序，并重新搜索打开',
          showCancel: false,
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '录音失败!',
          showCancel: false
        });
      }
    });
    var bufferNum = 0;
    //录音分片
    recorderManager.onFrameRecorded((res) => {
      bufferNum++;
      // 是否是最后一片
      var isLastFrame = res.isLastFrame;
      // 如果不是人为停止
      if (isLastFrame && that.data.recordState != 0) {
        isLastFrame = false;
        //开始录音
        recorderManager.start(that.data.recordParam);
      }
      fileSystemManager.writeFileSync(
        `${wx.env.USER_DATA_PATH}/recorder.mp3`,
        res.frameBuffer
      );
      api.uploadRecordFrame(`${wx.env.USER_DATA_PATH}/recorder.mp3`, that.data.userId, that.data.outvisitTaskId, bufferNum).then(res => {
        var data = JSON.parse(res.data);
        if (data.code == 0) {
          var tempsFile = wx.getStorageSync("tempsFile-" + that.data.userId + "-" + that.data.outvisitTaskId);
          if (!tempsFile) {
            var tempsFile = [];
          }
          tempsFile.push(data.data.msg);
          wx.setStorageSync("originalFilePath-" + that.data.userId + "-" + that.data.outvisitTaskId, data.data.message);
          wx.setStorageSync("tempsFile-" + that.data.userId + "-" + that.data.outvisitTaskId, tempsFile);
        }
        // 如果是最后一片则合并
        if (isLastFrame) {
          that.data.prePage.mergeRecord();
        }
      }).catch(res => {
        // 如果是最后一片则合并
        if (isLastFrame) {
          that.data.prePage.mergeRecord();
        }
      });
    });
    // 清空停止录音回调
    recorderManager.onStop();
  },

  //停止录音
  recordStop: function () {
    var that = this;
    that.setData({
      recordState: 0
    }, () => {
      recorderManager.stop();
      recorderManager.onStop((res) => {
        //结束录音计时 
        clearInterval(that.setInter);
        that.setData({
          recordTime: 0
        });
        // 返回录音列表页
        wx.navigateBack({
          delta: 1
        });
      });
    });
  },

  // 继续录音
  recordResume: function () {
    var that = this;
    that.setData({
      recordState: 1
    });
    //开始录音计时
    that.recordingTimer();
    //继续录音
    recorderManager.resume();
  },

  //录音计时器
  recordingTimer: function () {
    var that = this;
    var recordTimeBegin = 0;
    if (that.data.recordTime > 0) {
      recordTimeBegin = (Date.parse(new Date()) / 1000) - that.data.recordTime;
    } else {
      recordTimeBegin = Date.parse(new Date()) / 1000;
    }
    that.setData({
      recordTimeBegin: recordTimeBegin
    });
    //将计时器赋值给setInter
    that.setInter = setInterval(
      function () {
        var time = (Date.parse(new Date()) / 1000) - that.data.recordTimeBegin;
        that.setData({
          recordTime: time
        })
      }
    , 1000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.recordState == 1 || this.data.recordState == 2) {
      this.setData({
        recordState: 0
      });
      recorderManager.stop();
      recorderManager.onStop();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})